<template>
  <view class="error-container">
    <!-- 空状态图标 -->
    <view v-if="!showCreateForm" class="empty-icon">
      <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/ef486b398ce14efab153ef7f23f8ec70.jpg" mode="aspectFit" class="icon-image"></image>
    </view>

    <!-- 标题和描述 -->
    <view v-if="!showCreateForm" class="content-section">
      <text class="title">暂无宗亲会</text>
      <text class="description">{{ !isClanLeader() ? "您当前还没有创建宗亲会的权限" : "" }}</text>
    </view>

    <!-- 操作按钮 -->
    <view v-if="!showCreateForm" class="action-section">
      <view
        v-if="isClanLeader() && isClanCreate"
        class="action-btn primary"
        @click="handleCreateClan"
      >
        <text class="btn-text">创建宗亲会</text>
      </view>
      <!-- <view class="action-btn primary" @click="handleApply" v-if="!isClanLeader()">
        <text class="btn-text">申请入会</text>
      </view> -->
    </view>

    <!-- 创建宗亲会表单 -->
    <view v-if="showCreateForm" class="create-form-section">
      <view class="form-header">
        <text class="form-title">创建宗亲会</text>
        <view class="back-btn" @click="handleBack">
          <text class="back-text">返回</text>
        </view>
      </view>

      <clanSionFrom ref="formRef" />

      <view class="form-actions">
        <view class="action-btn secondary" @click="handleBack">
          <text class="btn-text">取消</text>
        </view>
        <view class="action-btn primary" @click="handleSubmitForm">
          <text class="btn-text">提交</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import ClanAssociationAPI from "@/api/genealogy/clanAssociation";
import clanSionFrom from "./component/clanSionFrom.vue";

// 用户信息接口
interface UserInfo {
  id?: string;
  username?: string;
  areaCodeScope?: Number;
  [key: string]: any;
}

// 定义宗亲会信息接口
interface ClanAssociationInfo {
  id?: string;
  name?: string;
  location?: string;
  address?: string;
  longitude?: number;
  latitude?: number;
  logo?: string;
  description?: string;
  history?: string;
  hasJoined?: string;
  [key: string]: any;
}

// 定义 emits
interface Emits {
  (e: "refresh"): void;
}

const emit = defineEmits<Emits>();

const userInfo = ref<UserInfo>({});
const clanAssoInfo = ref<ClanAssociationInfo>({});
const isClanCreate = ref(false);
const showCreateForm = ref(false);
const formRef = ref();

// 获取用户信息
const getUserInfo = () => {
  try {
    const userInfoStr = uni.getStorageSync("user-info");
    if (userInfoStr) {
      // 如果 userInfoStr 是字符串，需要解析为对象
      if (typeof userInfoStr === "string") {
        userInfo.value = JSON.parse(userInfoStr);
      } else {
        userInfo.value = userInfoStr;
      }
      console.log("用户信息:", userInfo.value);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
};

// 判断是否为族长
const isClanLeader = () => {
  const isLeader = userInfo.value.areaCodeScope === 6;
  return isLeader;
};

// 检查是否已创建宗亲会
const checkClanCreated = (res: any) => {
  if (res === null || res === undefined || (Array.isArray(res) && res.length === 0)) {
    console.log("res", res);
    isClanCreate.value = true;
    console.log("未创建宗亲会，显示创建按钮");
  } else {
    isClanCreate.value = false;
    console.log("已创建宗亲会，隐藏创建按钮");
  }
};

// 获取宗亲会信息
const getClanAssociation = async () => {
  try {
    const res = await ClanAssociationAPI.getPage();
    console.log("宗亲会信息:", res);

    // 检查是否已创建宗亲会
    checkClanCreated(res);

    // 如果 res 为 null 或 undefined，设置为空对象
    if (res === null || res === undefined) {
      clanAssoInfo.value = {} as ClanAssociationInfo;
    } else {
      clanAssoInfo.value = res as ClanAssociationInfo;

      // 确保地址字段被正确赋值
      if ((res as any).address) {
        clanAssoInfo.value.location = (res as any).address;
      }
    }
  } catch (error) {
    console.error("获取宗亲会信息失败:", error);
    clanAssoInfo.value = {} as ClanAssociationInfo;
    checkClanCreated(null);
  }
};

// 创建宗亲会
const handleCreateClan = () => {
  showCreateForm.value = true;
};

// 申请入会
const handleApply = () => {
  uni.navigateTo({
    url: "/pages/work/clan/apply",
  });
};

// 返回按钮
const handleBack = () => {
  showCreateForm.value = false;
  // 重置表单
  if (formRef.value) {
    formRef.value.resetForm();
  }
};

// 提交表单
const handleSubmitForm = async () => {
  if (!formRef.value) {
    uni.showToast({
      title: "表单未加载",
      icon: "error",
    });
    return;
  }

  // 验证表单
  const { isValid, errors } = formRef.value.validateForm();

  if (!isValid) {
    uni.showToast({
      title: errors[0] || "请填写必填项",
      icon: "error",
    });
    return;
  }

  // 获取表单数据
  const formData = formRef.value.getFormData();

  try {
    uni.showLoading({
      title: "提交中...",
    });

    // 调用创建宗亲会API
    await ClanAssociationAPI.createClan(formData).then((result) => {
      uni.hideLoading();
      uni.showToast({
        title: "创建成功",
        icon: "success",
      });

      // 重新获取宗亲会信息
      getClanAssociation();

      // 隐藏表单
      showCreateForm.value = false;

      // 重置表单
      formRef.value.resetForm();

      // 通知父组件刷新数据
      emit("refresh");
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "创建失败，请重试",
      icon: "error",
    });
    console.error("创建宗亲会失败:", error);
  }
};

onMounted(() => {
  getUserInfo();
  getClanAssociation();
});
</script>

<style scoped>
.error-container {
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
}

.empty-icon {
  margin-bottom: 60rpx;
  animation: float 3s ease-in-out infinite;
}

.icon-image {
  width: 200rpx;
  height: 200rpx;
  opacity: 0.8;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.content-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.description {
  display: block;
  font-size: 28rpx;
  line-height: 1.6;
  max-width: 600rpx;
  margin: 0 auto;
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin-bottom: 80rpx;
  width: 100%;
  max-width: 500rpx;
}

.action-btn {
  padding: 24rpx 40rpx;
  border-radius: 50rpx;
  text-align: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.action-btn.primary {
  background: #4d80f0;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.2);
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10rpx);
}

.action-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
}

/* 创建表单样式 */
.create-form-section {
  width: 100%;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.back-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
}

.back-btn:active {
  background-color: #e0e0e0;
}

.back-text {
  font-size: 26rpx;
  color: #666;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  background-color: #f8f9fa;
}

.form-actions .action-btn {
  flex: 1;
  margin: 0;
}

.tips-section {
  width: 100%;
  max-width: 600rpx;
}

.tip-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

.tip-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.tip-text {
  font-size: 26rpx;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .error-container {
    padding: 40rpx 30rpx;
  }

  .title {
    font-size: 40rpx;
  }

  .description {
    font-size: 26rpx;
  }

  .action-btn {
    padding: 20rpx 32rpx;
  }

  .btn-text {
    font-size: 28rpx;
  }

  .create-form-section {
    max-width: 100%;
  }
}
</style>
